<template>
    <div class="authority">
        <div class="gva-search-box">
            <el-form ref="searchForm" label-width="90" :inline="true"
                style="display: flex;flex-direction: column;align-items: center;">
                <div>
                    <el-form-item label="单位名称">
                        <el-select v-model="searchInfo.unitIds" filterable multiple placeholder="请选择"
                            style="width: 220px;" class="tags-select-input" collapse-tags>
                            <el-option v-for="item in unitData" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="年份">
                        <el-date-picker format="YYYY" value-format="YYYY" v-model="searchInfo.year" type="year"
                            placeholder="请选择" style="width: 220px;" />
                    </el-form-item>
                    <el-form-item label="办公楼名称">
                        <el-input v-model="searchInfo.buildingName" placeholder="请输入" style="width: 220px;" />
                    </el-form-item>
                </div>
                <div>
                    <el-form-item label="项目名称">
                        <el-input v-model="searchInfo.name" placeholder="请输入" style="width: 220px;" />
                    </el-form-item>
                    <el-form-item label="审批状态">
                        <el-select v-model.number="searchInfo.examineStatus" placeholder="请选择" style="width: 220px;">
                            <el-option :key="2" label="待审批" :value="2" />
                            <el-option :key="1" label="已审批" :value="1" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="审批结果">
                        <el-select v-model.number="searchInfo.examineResult" placeholder="请选择" style="width: 220px;">
                            <el-option :key="1" label="通过" :value="1" />
                            <el-option :key="2" label="未通过" :value="2" />
                        </el-select>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" icon="search" @click="onSubmit">
                        查询
                    </el-button>
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="gva-table-box unit">
            <div class="ant-alert-info">
                <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
                    <div class="pop-content">
                        <div class="pop-title">自定义列</div>
                        <div class="check-list">
                            <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                    <template #reference>
                        <div class="anticon">
                            <el-icon size="16" color="#1890ff">
                                <Setting />
                            </el-icon>
                            <div style="margin-left: 2px;">自定义列</div>
                        </div>
                    </template>
                </el-popover>
            </div>
            <el-table :data="tableData" row-key="id">
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="年份" prop="year"
                    v-if="checkedColumns.includes('年份')"></el-table-column>
                <el-table-column align="left" label="申请单位" prop="unitName" show-overflow-tooltip
                    v-if="checkedColumns.includes('申请单位')"></el-table-column>
                <el-table-column align="left" label="办公楼名称" prop="buildingName" show-overflow-tooltip
                    v-if="checkedColumns.includes('办公楼名称')"></el-table-column>
                <el-table-column align="left" label="项目名称" prop="name" show-overflow-tooltip
                    v-if="checkedColumns.includes('项目名称')"></el-table-column>
                <el-table-column align="left" label="申请时间" v-if="checkedColumns.includes('申请时间')">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.applyAt) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="联系人" prop="contacts"
                    v-if="checkedColumns.includes('联系人')"></el-table-column>
                <el-table-column align="left" label="联系电话" prop="contactUs"
                    v-if="checkedColumns.includes('联系电话')"></el-table-column>
                <el-table-column align="left" label="审批状态" v-if="checkedColumns.includes('审批状态')">
                    <template #default="scope">
                        {{ scope.row.examineStatus == 1 ? '已审批' : '待审批' }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="审批结果" v-if="checkedColumns.includes('审批结果')">
                    <template #default="scope">
                        {{ scope.row.examineResult == 1 ? '通过' : '未通过' }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="附件" v-if="checkedColumns.includes('附件')">
                    <template #default="scope">
                        <span style="color: #3b82f6;cursor: pointer;" @click="seeFile(scope.row.id)">查看</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="操作" v-if="checkedColumns.includes('操作')">
                    <template #default="scope">
                        <span v-if="scope.row.examineStatus == 1" style="color: #3b82f6;cursor: pointer;"
                            @click="seeDetail(scope.row, 'detail')">详情</span>
                        <span v-else style="color: #3b82f6;cursor: pointer;" @click="seeDetail(scope.row)">审批</span>
                    </template>
                </el-table-column>
            </el-table>
            <div class="gva-pagination">
                <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total"
                    layout="prev, pager, next" @current-change="handleCurrentChange" />
            </div>
        </div>
        <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose" :show-close="false"
            class="sb-draw">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">改变房屋布局用途审批</span>
                    <div>
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                    </div>
                </div>
            </template>
            <el-form v-if="dialogFormVisible && active == 1" :disabled="isDetail" ref="yyglForm" label-width="150"
                :model="form1" :rules="rules">
                <div class="section-title">基本信息</div>
                <el-form-item label="项目名称">
                    <el-input v-model="form.name" disabled placeholder="请输入" style="width: 500px;" />
                </el-form-item>
                <el-form-item label="维修办公楼">
                    <el-select v-model="form.buildingId" placeholder="请选择" disabled style="width: 500px;">
                        <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="改变类型">
                    <el-radio-group v-model="form.changeType" class="ml-4" disabled>
                        <el-radio :value="1" size="large">改变布局和用途</el-radio>
                        <el-radio :value="2" size="large">改变布局</el-radio>
                        <el-radio :value="3" size="large">改变用途</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="联系人">
                    <el-input v-model="form.contacts" disabled placeholder="请输入" style="width: 500px;" />
                </el-form-item>
                <el-form-item label="联系电话">
                    <el-input v-model="form.contactUs" disabled placeholder="请输入" style="width: 500px;" />
                </el-form-item>
                <el-form-item label="变更情况说明">
                    <el-input v-model="form.notes" disabled type="textarea" :rows="3" placeholder="请输入"
                        style="width: 500px;" />
                </el-form-item>

                <div class="section-title">审批意见</div>
                <el-form-item label="是否通过变更布局" prop="examineResult">
                    <el-radio-group v-model.number="form1.examineResult" class="ml-4">
                        <el-radio :value="1" size="large">通过</el-radio>
                        <el-radio :value="2" size="large">不通过</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="审批说明">
                    <el-input v-model="form1.detailExamine[0].examineNotes" type="textarea" :rows="3" placeholder="请输入"
                        style="width: 500px;" />
                </el-form-item>
                <el-form-item label="" style="margin-top: 50px;">
                    <el-button type="primary" @click="enterDialog">提交审批</el-button>
                    <el-button @click="closeDialog">关闭</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>

        <el-drawer v-model="dialog3" :size="1000" :before-close="handleClose3" :show-close="false"
            class="loudong-drawer">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">查看附件</span>
                    <div>
                        <el-button @click="closeDialog3">取消</el-button>
                    </div>
                </div>
            </template>
            <el-table :data="fjList" row-key="id">
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="文件名" prop="fileName">
                </el-table-column>
                <el-table-column align="left" label="文件类型">
                    <template #default="scope">
                        {{ fileTypes[scope.row.fileType] }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="上传时间">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.createdAt) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" fixed="right" label="操作">
                    <template #default="scope">
                        <el-button type="primary" link icon="download" @click="download(scope.row)">
                            下载
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-drawer>
    </div>
</template>
<script setup>
import {
    buildingAll,
    unitLists
} from '@/api/unit'
import {
    optionList,
    declareMediumApply,
    declareMedium,
    declareMediumFile,
    declareMediumDetail,
    maintainDeclareMedium,
    declareMediumExamine
} from '@/api/yewuguanli'

import { reactive, ref, onMounted, computed } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { buildTimeList, countdownEmits, ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import { Document, Memo } from '@element-plus/icons-vue'
import { formatTimestamps } from '@/utils/format'
import { fileTypes } from '@/utils/constant';
defineOptions({
    name: 'Yygl'
})
const appStore = useAppStore()

const searchInfo = ref({
    name: '',
    type: 3,
    unitIds: [],
    unitName: '',
    buildingName: '',
    examineStatus: '',
    examineResult: ''
})

const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)
let validateImage = (rule, value, callback) => {
    if (fileList1.value.length == 0) {
        callback(new Error('请上传文件'))
    } else {
        callback()
    }
}
const rules = reactive({
    examineResult: [{ required: true, message: '请选择是否通过变更布局', trigger: 'change' }]
})
let validatePass = (rule, value, callback) => {
    callback()
}
const rules2 = reactive({
    name: [{ required: true, validator: validatePass, trigger: 'blur' }],
    profile: [{ required: true, validator: validatePass, trigger: 'blur' }],
    funding: [{ required: true, validator: validatePass, trigger: 'blur' }]
})
const active = ref(1)
const form = ref({
    type: 0,
    examineResult: 1,
    buildingName: '',
    name: '',
    adoptFunding: '',
    declareId: '',
    examineNotes: ''
})

function tabChange() {

}
const declareDetail = ref([
    // {
    //     system: '承重系统',
    //     name: '',
    //     profile: '',
    //     funding: '',
    //     notes: ''
    // },
    // {
    //     system: '建筑消防系统',
    //     name: '',
    //     profile: '',
    //     funding: '',
    //     notes: ''
    // }
])
const totalNum = computed(() => {
    return declareDetail.value.reduce((prev, next) => prev + Number(next.funding), 0)
})
const form1 = ref({
    adopt: 4,
    declareId: '',
    detailExamine: [
        {
            adopt: '',
            adoptFunding: '',
            detailId: '',
            examineNotes: ''
        }
    ]
})

const initForm = () => {
    yyglForm.value.resetFields()
    form1.value = {
        type: 0,
        examineResult: 1,
        buildingName: '',
        name: '',
        adoptFunding: '',
        declareId: '',
        examineNotes: '',
        detailExamine: [
            {
                adopt: '',
                adoptFunding: '',
                detailId: '',
                examineNotes: ''
            }
        ]
    }
}

const checkedColumns = ref(['序号', '年份', '申请单位', '办公楼名称', '项目名称', '申请时间', '联系人', '联系电话', '审批状态', '审批结果', '附件', '操作'])

if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).gbbjytsp) {
    checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).gbbjytsp
}
const columns = ref(['序号', '年份', '申请单位', '办公楼名称', '项目名称', '申请时间', '联系人', '联系电话', '审批状态', '审批结果', '附件', '操作'])
const handleColumnsChange = (val) => {
    let obj = {

    }
    if (localStorage.getItem('columnData')) {
        obj = JSON.parse(localStorage.getItem('columnData'))
    }
    obj.gbbjytsp = val
    localStorage.setItem('columnData', JSON.stringify(obj))
}

const isEdit = ref(false)
const dialogTitle = ref('大中修项目申报')
const addUnit = () => {
    dialogTitle.value = '大中修项目申报'
    isEdit.value = false
    dialogFormVisible.value = true
}

const closeDialog = () => {
    initForm()
    dialogFormVisible.value = false
}

const handleClose = (done) => {
    initForm()
    done()
}
const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
    const res = await maintainDeclareMedium({
        pageNumber: page.value,
        pageSize: pageSize.value,
        ...searchInfo.value
    })
    if (res.code == 200) {
        tableData.value = res.result.data
        total.value = res.result.total
    }
}
getTableData()
const buildList = ref([])
const checkOptions = ref([])
const unitData = ref([])
onMounted(() => {
    optionList().then(res => {
        checkOptions.value = res.result
    })
    buildingAll().then(res => {
        buildList.value = res.result
    })
    unitLists().then(res => {
        unitData.value = res.result.data
    })
})

const onSubmit = () => {
    page.value = 1
    getTableData()
}
const onReset = () => {
    page.value = 1
    searchInfo.value = {
        name: '',
        type: 3,
        unitIds: [],
        unitName: '',
        buildingName: ''
    }
    getTableData()
}
const yyglForm = ref(null)
function next() {
    yyglForm.value.validate(async (valid) => {
        if (valid) {
            if (active.value == 1) {
                const selectedLabels = checkOptions.value.filter(option => form1.value.checkOptions.includes(option.id)).map(option => option.name)
                declareDetail.value = selectedLabels.map(item => {
                    return {
                        system: item,
                        name: '',
                        profile: '',
                        funding: '',
                        notes: ''
                    }
                })
            }
            if (active.value == 2) {
                let flag = declareDetail.value.some(item => {
                    return !item.name || !item.funding || !item.profile
                })
                if (flag) {//表示没填完整
                    ElMessage({
                        type: 'info',
                        message: '请填写完整信息'
                    })
                    return
                }
                form1.value.declareDetail = declareDetail.value
                form1.value.totalFunding = totalNum.value
            }
            if (active.value == 3) {
                let declareFile = []
                if (fileList1.value.length > 0) {
                    declareFile.push({ fileName: fileList1.value[0].name, fileType: 1, fileUrl: fileList1.value[0].response.result })
                }
                if (fileList2.value.length > 0) {
                    declareFile.push({ fileName: fileList2.value[0].name, fileType: 2, fileUrl: fileList2.value[0].response.result })
                }
                if (fileList3.value.length > 0) {
                    declareFile.push({ fileName: fileList3.value[0].name, fileType: 3, fileUrl: fileList3.value[0].response.result })
                }
                if (fileList4.value.length > 0) {
                    declareFile.push({ fileName: fileList4.value[0].name, fileType: 4, fileUrl: fileList4.value[0].response.result })
                }
                if (fileList5.value.length > 0) {
                    declareFile.push({ fileName: fileList5.value[0].name, fileType: 5, fileUrl: fileList5.value[0].response.result })
                }
                form1.value.declareFile = declareFile
                declareMediumApply(form1.value).then(res => {
                    dialogFormVisible.value = false
                    active.value = 1
                })
            }
            if (active.value < 3) {
                active.value++
            }
            //   let res
            //   if (isEdit.value) {
            //     res = await updateDyn(form.value)
            //   } else {
            //     res = await createDy(form.value)
            //   }
            //   if (res.code == 200) {
            //     ElMessage({
            //       type: 'success',
            //       message: isEdit.value ? '编辑成功' : '添加成功!'
            //     })
            //     getTableData()
            //   }
            //initForm()
            //dialogFormVisible.value = false
        }
    })
}
function downloadTable() {

}
function prev() {
    active.value--
}
const fileList1 = ref([])
const fileList2 = ref([])
const fileList3 = ref([])
const fileList4 = ref([])
const fileList5 = ref([])

function uploadSuccess1(res) {

}
function uploadSuccess2(res) {

}
const dialog3 = ref(false)
const fjList = ref([])
function seeFile(id) {
    declareMediumFile(id).then(res => {
        fjList.value = res.result
        dialog3.value = true
    })
}
function handleClose3() {
    dialog3.value = false
}
function closeDialog3() {
    dialog3.value = false
}
const download = (row) => {
    window.open(row.fileUrl)
}
const typeList = ref([])
const isDetail = ref(false)
function seeDetail(row, val) {
    isDetail.value = val == 'detail' ? true : false
    form.value = JSON.parse(JSON.stringify(row))
    form1.value.declareId = row.id
    form1.value.examineResult = row.examineResult || 1
    form1.value.detailExamine[0].examineNotes = row.examineNotes
    dialogFormVisible.value = true
}
const enterDialog = async () => {
    yyglForm.value.validate(async (valid) => {
        if (valid) {
            let res = await declareMediumExamine(form1.value)
            if (res.code == 200) {
                ElMessage({
                    type: 'success',
                    message: '审批成功'
                })
                dialogFormVisible.value = false
                getTableData()
            }
            //   if (isEdit.value) {
            //     res = await declareMediumExamine(form.value)
            //   } else {
            //     res = await createDy(form.value)
            //   }
            //   if (res.code == 200) {
            //     ElMessage({
            //       type: 'success',
            //       message: isEdit.value ? '编辑成功' : '添加成功!'
            //     })
            //     getTableData()
            //   }
            //   initForm()
            //   dialogFormVisible.value = false
        }
    })
}
</script>

<style lang="scss">
.ant-alert-info {
    display: flex;
    justify-content: end;
    align-items: center;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    color: #1890ff;
    padding: 5px;

    .anticon {
        display: flex;
        align-items: center;
        cursor: pointer;
    }
}

.section-title {
    font-weight: bold;
    font-size: 18px;
    line-height: 33px;
    padding: 8px 0 4px 14px;
    color: #4E7DFD;
    position: relative;
}

.section-title:before {
    content: '';
    position: absolute;
    top: 17px;
    left: 0;
    width: 6px;
    height: 14px;
    border-radius: 3px;
    background: #4E7DFD;
}

.sb-draw {
    .title {
        font-size: 16px;
        padding-bottom: 10px;
        margin-bottom: 10px;
        border-bottom: 1px solid #e4e7ed;
    }
}
</style>